<?php

namespace app\modules\agent\controllers;

use app\models\Agent;
use app\models\AgentLog;
use app\models\AgentProfileForm;
use Yii;
use yii\web\Response;

/**
 * 用户信息管理
 * Class IdentityController
 * @package app\modules\agent\controllers
 */
class IdentityController extends BaseController
{
    /**
     * 代理商退出
     * @return Response
     */
    public function actionLogout()
    {
        AgentLog::info($this->agent->id, 'LOGOUT', '退出');
        $this->agent->logout();
        $this->agent->setReturnUrl(['/agent']);
        return $this->redirect(['/agent/login']);
    }

    /**
     * 用户设置
     * @return string
     */
    public function actionProfile()
    {
        $model = new AgentProfileForm();
        $agent = Agent::findOne(['id' => $this->agent->id]);
        $model->setAttributes($agent->attributes, false);
        if ($model->load($this->post()) && $model->validate() && $model->save()) {
            AgentLog::info($this->agent->id, 'SAVE_USER', '保存账号信息', print_r($model->attributes, true));
            // 更新Session
            $agent->refresh();
            Yii::$app->agent->setIdentity($agent);
            Yii::$app->session->addFlash('success', '用户信息已保存。');
        }
        return $this->render('profile', [
            'model' => $model
        ]);
    }
}
